package cn.workreport.util;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;

/**
 * 描述【网络请求工具类】
 *
 * @author lihuanyao
 * @time 2021/11/26 21:14
 */
public class HttpServletUtil {

    /**
     *  获取 Response
     * @return
     */
    public static HttpServletResponse  getResponse(){
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getResponse();

    }
    /**
     *  获取 Request
     * @return
     */
    public static HttpServletRequest  getRequest(){
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getRequest();

    }

    /**
     *  获取导出使用的输出流
     * @param fileName
     * @return
     * @throws IOException
     */
    public static ServletOutputStream getExportOutputStream (String fileName) throws IOException {
        HttpServletResponse response = getResponse();
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
        return response.getOutputStream();
    }
    /**
     *  获取导出使用的输出流（无参接口）
     * @return
     * @throws IOException
     */
    public static ServletOutputStream getExportOutputStream () throws IOException {
       String  fileName = "导出_"+DateUtil.format(new Date(), DatePattern.CHINESE_DATE_PATTERN);
        return getExportOutputStream(fileName);
    }
}
